package logic

import (
	"context"

	"paper-pro/app/usercenter/model"
	"paper-pro/app/usercenter/rpc/internal/svc"
	"paper-pro/app/usercenter/rpc/pb"
	"paper-pro/app/usercenter/rpc/usercenter"
	"paper-pro/pkg/tool"
	"paper-pro/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

var ErrGenerateTokenError = xerr.NewErrMsg("生成token失败")
var ErrUsernamePwdError = xerr.NewErrMsg("账号或密码不正确")
var ErrUserNoExistsError = xerr.NewErrMsg("用户不存在")

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *pb.LoginReq) (*pb.LoginResp, error) {
	var err error
	user, err := l.svcCtx.UserModel.FindOneByNickname(l.ctx, in.Nickname)
	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"根据用户名获取用户信息失败，nickname:%s, err:%v", in.Nickname, err)
	}
	if user == nil {
		return nil, errors.Wrapf(ErrUserNoExistsError, "nickname:%s", in.Nickname)
	}
	// todo: 将前端密码用秘钥解密
	if inPassword, err := tool.Md5ByString(in.Password); err != nil || inPassword != user.Password {
		return nil, errors.Wrap(ErrUsernamePwdError, "密码匹配出错")
	}

	generateTokenLogic := NewGenerateTokenLogic(l.ctx, l.svcCtx)
	tokenResp, err := generateTokenLogic.GenerateToken(&usercenter.GenerateTokenReq{
		UserId: user.Id,
	})
	if err != nil {
		return nil, errors.Wrapf(ErrGenerateTokenError, " GenerateToken userId: %d", user.Id)
	}

	return &pb.LoginResp{
		AccessToken:  tokenResp.AccessToken,
		AccessExpire: tokenResp.AccessExpire,
		RefreshAfter: tokenResp.RefreshAfter,
	}, nil
}
